<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/21
 * Time: 16:14
 */

if (!defined('IN_IA')) {
    exit('Access Denied');
}

class Order_OP_MxShopPage extends WebPage
{

    public function pay()
    {
        global $_W, $_GPC;
        $uniacid = $_W['platformid'];
        $id = intval($_GPC['id']);
        if(empty($id)){
            show_json(0, '订单不存在');
        }

        $order = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order') . ' WHERE id=:id AND deleted=0', array(':id'=>$id));
        if($order['status'] != 1){
            show_json(0, '订单状态已变更，无法确认付款');
        }
        $log = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_paylog') . ' WHERE `module`=:module AND `tid`=:tid limit 1', array(':module' => 'mx_shop', ':tid' => $order['ordersn']));
        if (empty($log))
        {
            if ($_W['ispost'])
            {
                show_json(0, '支付出错,请重试!');
            }
            else
            {
                $this->message('支付出错,请重试!', mobileUrl('order'));
            }
        }

        plog('sorder.order_op.pay', '订单确认付款 ID: ' . $id);

        $record = array();
        $record['status'] = '1';
        $record['type'] = 'cash';
        pdo_update('mx_shop_service_paylog', $record, array('plid' => $log['plid']));

        $data_goods = array(
            'isnormal'	=>2,
            'updatetime'	=>time()
        );
        //pdo_update('mx_shop_service_goods', $data_goods, array('id' => $order['goods_id'], 'uniacid' => $order['uniacid']));

        $typeprice = pdo_fetch('SELECT * FROM '. tablename('mx_shop_service_goods_type_price') . ' WHERE id=:id AND status=1 AND deleted=0', array(':id'=>$order['price_id']));

        $integral = intval($typeprice['integral']);
        if($integral>0){
            m('userinfo')->setCredit($order['uid'], 'credit1', $integral, array($_W['member']['uid'], $order['goods_name'] . '消费后赠送积分' . $integral));
        }

        $data = array(
            'paytype'=>19,
            'status'=>2,
            'ispay'=>1,
            'upstatus'=>1,
            'paytime'=>time(),
        );
        pdo_update('mx_shop_service_order', $data, array('id'=>$id));

        show_json(1);
    }

    public function refundpass()
    {
        global $_W, $_GPC;

        $id = intval($_GPC['id']);
        if(empty($id)){
            show_json(0, '订单不存在');
        }

        $order = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order') . ' WHERE id=:id AND deleted=0', array(':id'=>$id));
        if($order['status'] != 5){
            show_json(0, '订单状态已变更，无法通过申请');
        }

        $refund = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order_refund') . ' WHERE orderid=:oid  AND status=0 AND isclose=0', array(':oid'=>$id));
        if(empty($refund)){
            show_json(0, '该订单维权申请不存在');
        }

        $realprice = $order['realprice'];
        $order_price = $order['price'];
        $ordersn = $order['ordersn'];

        //维权完成 - 退款操作
        if ($order['paytype'] == 3)
        {
            m('userinfo')->setCredit($order['uid'], 'credit2', $realprice, array(0, $order['mendian_name'] . '退款: ' . $realprice . '元 订单号: ' . $order['ordersn']));

            $result = true;
        }
        else if ($order['paytype'] == 24)
        {
            if ($order['apppay'] == 2)
            {
                $result = m('finance')->wxapp_refund($order['openid'], $ordersn, $refund['refundno'], $order_price * 100, $realprice * 100, (!(empty($order['apppay'])) ? true : false));
            }
            else
            {
                if ($realprice > 0)
                {
                    $result = m('finance')->refund($order['openid'], $ordersn, $refund['refundno'], $order_price * 100, $realprice * 100, (!(empty($order['apppay'])) ? true : false));
                }
            }
            $refundtype = 2;
        }
        else if ($order['paytype'] == 38)
        {
            $sec = m('common')->getSec();
            $sec = iunserializer($sec['sec']);
            if (!(empty($order['apppay'])))
            {
                if (empty($sec['app_alipay']['private_key']) || empty($sec['app_alipay']['appid']))
                {
                    show_json(0, '支付参数错误，私钥为空或者APPID为空!');
                }
                $params = array('out_request_no' => time(), 'out_trade_no' => $ordersn, 'refund_amount' => $realprice, 'refund_reason' => $order['mendian_name'] . '退款: ' . $realprice . '元 订单号: ' . $order['ordersn']);
                $config = array('app_id' => $sec['app_alipay']['appid'], 'privatekey' => $sec['app_alipay']['private_key'], 'publickey' => '', 'alipublickey' => '');
                $result = m('finance')->newAlipayRefund($params, $config);
            }
            else
            {
                if (empty($order['transid']))
                {
                    show_json(0, '仅支持 升级后此功能后退款的订单!');
                }
                $setting = uni_setting($_W['platformid'], array('payment'));
                if (!(is_array($setting['payment'])))
                {
                    return error(1, '没有设定支付参数');
                }
                $alipay_config = $setting['payment']['alipay'];
                $batch_no_money = $realprice * 100;
                $batch_no = date('Ymd') . 'RF' . $order['id'] . 'MONEY' . $batch_no_money;
                $res = m('finance')->AlipayRefund(array('trade_no' => $order['transid'], 'refund_price' => $realprice, 'refund_reason' => $order['mendian_name'] . '退款: ' . $realprice . '元 订单号: ' . $order['ordersn']), $batch_no, $alipay_config);
                if (is_error($res))
                {
                    show_json(0, $res['message']);
                }
                show_json(1, array('url' => $res));
            }
        }
        else
        {
            if ($realprice < 1)
            {
                show_json(0, '退款金额必须大于1元，才能使用微信企业付款退款!');
            }

            if (0 < $realprice)
            {
                $result = m('finance')->pay($order['openid'], 1, $realprice * 100, $refund['refundno'], $order['mendian_name'] . '退款: ' . $realprice . '元 订单号: ' . $order['ordersn']);
            }
            $refundtype = 1;
        }
        if (is_error($result))
        {
            show_json(0, $result['message']);
        }

        if ($order['deductcredit'] > 0)
        {
            m('userinfo')->setCredit($order['uid'], 'credit1', $order['deductcredit'], array('0', $order['mendian_name'] . '购物返还抵扣积分 积分: ' . $order['deductcredit'] . ' 抵扣金额: ' . $order['deductprice'] . ' 订单号: ' . $order['ordersn']));
        }

        $log = '订单退款 ID: ' . $order['id'] . ' 订单号: ' . $order['ordersn'];
        plog('sorder.order_op.refundpass', $log);

        $refdata = array(
            'message' => $_GPC['remark'],
            'opname' => $_W['username'],
            'optime' => time(),
            'status' => 1
        );

        //优惠券
        if(!empty($order['couponid'])){

            pdo_update('ewei_shop_coupon_data', array('used'=>0, 'usetime'=>0), array('id'=>$order['id']));
        }

        plog('sorder.order_op.refundpass', '订单退款申请通过 ID: ' . $id);

        pdo_update('mx_shop_service_order_refund', $refdata, array('id'=>$refund['id']));

        pdo_update('mx_shop_service_goods', array('isnormal'=>1), array('id'=>$order['goods_id']));

        pdo_update('mx_shop_service_order', array('status'=>6, 'upstatus'=>5, 'cancetime'=>time()), array('id'=>$order['id']));

        show_json(1);

    }

    public function refundturn()
    {

        global $_W, $_GPC;

        $id = intval($_GPC['id']);
        if(empty($id)){
            show_json(0, '订单不存在');
        }

        if($_W['ispost']){

            if(empty($_GPC['remark'])){
                show_json(0, '请填写驳回原因');
            }

            $order = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order') . ' WHERE id=:id AND deleted=0', array(':id'=>$id));
            if(empty($order) || $order['status'] != 5){
                show_json(0, '订单状态已变更，无法驳回申请');
            }

            $refund = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order_refund') . ' WHERE orderid=:oid AND status=0 AND isclose=0', array(':oid'=>$id));
            if(empty($refund)){
                show_json(0, '该订单维权申请不存在');
            }

            plog('sorder.order_op.refundturn', '订单退款申请驳回 ID: ' . $id);

            $data = array(
                'message' => $_GPC['remark'],
                'opname' => $_W['config']['db']['master']['username'],
                'optime' => time(),
                'status' => 2,
                'isclose' => 2,
            );

            pdo_update('mx_shop_service_order_refund', $data, array('id'=>$refund['id']));

            pdo_update('mx_shop_service_order', array('status'=>$order['upstatus']), array('id'=>$id));

            show_json(1);
        }

        include $this->template();

    }

    public function close(){

        global $_W, $_GPC;

        $id = intval($_GPC['id']);
        if(empty($id)){
            show_json(0, '订单不存在');
        }

        $order = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order') . ' WHERE id=:id AND deleted=0', array(':id'=>$id));
        if(empty($order) || $order['status'] == 4){
            show_json(0, '订单已关闭');
        }

        pdo_update('mx_shop_service_order', array('status'=>4, 'canceltime'=>time()), array('id'=>$id));

        show_json(1);


    }

}